package club.monkeywood.service.buyer.impl;

import club.monkeywood.dataobject.Production;
import club.monkeywood.enums.ResponseEnum;
import club.monkeywood.enums.production.ProductionStatusEnum;
import club.monkeywood.exception.SellException;
import club.monkeywood.repository.ProductionInfoRepository;
import club.monkeywood.service.buyer.ProductionInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductionInfoServiceImpl implements ProductionInfoService {

    @Autowired
    ProductionInfoRepository repository;

    @Override
    public Production findById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Production> findByName(String name) {
        return repository.findByName(name);
    }

    @Override
    public Production findByid(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Production> findByIdIn(List<Integer> ids) {
        return repository.findByIdIn(ids);
    }

    @Override
    public Production findByCategoryId(Integer id) {
        return repository.findByCategoryId(id);
    }

    @Override
    public List<Production> findByCategoryIdIn(List<Integer> ids) {
        return repository.findByCategoryIdIn(ids);
    }

    @Override
    public List<Production> queryCategoryProductions() {
        return repository.queryCategoryProductions();
    }

    @Override
    public Page<Production> findAll(Pageable pageable) {
        return repository.findAll(pageable);
    }

    @Override
    public List<Production> findUPAll() {
        return repository.findByStatus(ProductionStatusEnum.UP.getCode());
    }

    @Override
    public Page<Production> findUPAll(Pageable pageable) {
        return repository.findByStatus(ProductionStatusEnum.UP.getCode(), pageable);
    }

    @Override
    public Production decreaseStock(Integer id, Integer count) {
        Production production = repository.findById(id).orElse(null);
        if (production == null) {
            throw new SellException(ResponseEnum.PRODUCT_NOT_EXIST);
        }
        Integer stock = production.getStock()-count;
        if(stock<0) {
            throw new SellException(ResponseEnum.PRODUCTION_INSUFFICIENT_STOCK);
        }

        production.setStock(stock);
        //增加销售量
        production.setSellCount(production.getSellCount()+count);
        repository.save(production);

        return production;
    }

}
